import matplotlib.pyplot as plt
import numpy as np

def read_and_process_data(log_file, st, ed):
    times = []
    max_sent_bytes = []
    min_sent_bytes = []
    median_sent_bytes = []
    
    current_max = 0
    current_min = float('inf')
    current_sent_bytes = []
    current_time = None

    with open(log_file, 'r') as f:
        for line in f:
            if line.startswith('Time'):
                # 获取当前时间
                time_str = line.split(":")[1].strip().replace('ns', '')
                current_time = int(time_str)
                
                # 记录统计值，记录上一个时间点的最大值、最小值和中位数
                times.append(current_time)
                max_sent_bytes.append(current_max)
                min_sent_bytes.append(current_min)
                median_sent_bytes.append(np.median(current_sent_bytes))
                
                # 重置统计值
                current_max = 0
                current_min = float('inf')
                current_sent_bytes = []
            elif 'sentBytes' in line:
                # 提取sentBytes
                parts = line.split()
                sent_bytes_str = parts[3].replace('KB', '')
                sent_bytes = float(sent_bytes_str) * 1024  # 转换成字节
                # 更新当前最大值、最小值和添加到当前的字节数据列表
                current_max = max(current_max, sent_bytes)
                current_min = min(current_min, sent_bytes)
                current_sent_bytes.append(sent_bytes)
        

    # 筛选时间范围
    times = np.array(times)
    max_sent_bytes = np.array(max_sent_bytes)
    min_sent_bytes = np.array(min_sent_bytes)
    median_sent_bytes = np.array(median_sent_bytes)
    mask = (times >= st) & (times <= ed)
    
    return times[mask], max_sent_bytes[mask], min_sent_bytes[mask], median_sent_bytes[mask]

def plot_sentbytes(times, max_sent_bytes, min_sent_bytes, median_sent_bytes, output_file):
    # 绘图
    plt.figure(figsize=(10, 6))
    
    # 绘制最大值曲线
    plt.plot(times, max_sent_bytes, marker='.', linestyle='-', color='b', label='Max SentBytes')
    
    # 绘制最小值曲线
    #plt.plot(times, min_sent_bytes, marker='x', linestyle='--', color='r', label='Min SentBytes')
    
    # 绘制中位数曲线
    # plt.plot(times, median_sent_bytes, marker='s', linestyle='-.', color='g', label='Median SentBytes')
    
    plt.xlabel('Time (ns)')
    plt.ylabel('SentBytes (Bytes)')
    plt.title('Max, Min, and Median SentBytes per Time Interval')
    plt.grid(True)
    plt.legend()
    
    # 保存图片
    plt.savefig(output_file, format='png')
    plt.close()

# 主程序
if __name__ == "__main__":
    log_file = 'run_bytes.log'
    st = 3010000000  # 起始时间（ns）
    ed = 4000000000  # 结束时间（ns）
    output_file = 'sentbytes_max_min_median_plot.png'

    times, max_sent_bytes, min_sent_bytes, median_sent_bytes = read_and_process_data(log_file, st, ed)
    plot_sentbytes(times, max_sent_bytes, min_sent_bytes, median_sent_bytes, output_file)
    print(f"图表已保存为 {output_file}")
